<template>
    <div>
        <el-container :style="{ height: pcHeight }">
            <el-main class="loginPC pd0 mg0">
                <img class="background-image" src="@/assets/img/wallhaven-8oky1j.webp" alt="背景图片" />

                <div class="login-card-container">
                    <el-card class="login-card" shadow="always">
                        <div class="card-header">
                            <h2 class="fs20 bold">就业职通车 企业登录</h2>
                        </div>

                        <div class="mode-switch mgT20">
                            <el-button-group>
                                <el-button
                                    :type="loginMode === 'login' ? 'primary' : ''"
                                    @click="switchMode('login')"
                                    :class="{ 'active-btn': loginMode === 'login' }"
                                    >登 录</el-button
                                >
                                <el-button
                                    :type="loginMode === 'register' ? 'primary' : ''"
                                    @click="switchMode('register')"
                                    :class="{ 'active-btn': loginMode === 'register' }"
                                    >注 册</el-button
                                >
                            </el-button-group>
                        </div>

                        <el-form
                            ref="dataFormRef"
                            :model="dataForm"
                            :rules="dataRules"
                            label-width="80px"
                            label-position="top"
                        >
                            <el-row class="pdB20">
                                <el-col :span="24" class="textL mgT10">
                                    <el-form-item
                                        :label="loginMode === 'login' ? '企业登录账号' : '注册账号'"
                                        prop="account"
                                    >
                                        <el-input
                                            ref="inputRef"
                                            v-model="dataForm.account"
                                            maxlength="20"
                                            :placeholder="
                                                loginMode === 'login' ? '请输入企业登录账号' : '请输入注册账号'
                                            "
                                            clearable
                                        ></el-input>
                                    </el-form-item>
                                    <el-form-item label="账号密码" prop="password" class="mgT25">
                                        <el-input
                                            password
                                            type="password"
                                            show-password
                                            v-model="dataForm.password"
                                            maxlength="20"
                                            placeholder="请输入登录账号密码"
                                            clearable
                                        ></el-input>
                                    </el-form-item>
                                    <el-form-item
                                        v-if="loginMode === 'register'"
                                        label="确认密码"
                                        prop="confirmPassword"
                                        class="mgT25"
                                    >
                                        <el-input
                                            password
                                            type="password"
                                            show-password
                                            v-model="dataForm.confirmPassword"
                                            maxlength="20"
                                            placeholder="请再次输入密码"
                                            clearable
                                        ></el-input>
                                    </el-form-item>
                                    <el-form-item label="验证码" prop="smsCode" class="mgT25">
                                        <el-input
                                            v-model.trim="dataForm.smsCode"
                                            maxlength="6"
                                            placeholder="请输入短信验证码"
                                            clearable
                                        >
                                            <template #append>
                                                <el-button
                                                    type="primary"
                                                    plain
                                                    class="mgL5"
                                                    style="opacity: 1; width: 100px"
                                                    :disabled="getCodeisWaiting"
                                                    @click="sendSmsCode"
                                                >
                                                    {{ getCodeText }}
                                                </el-button>
                                            </template>
                                        </el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="24" class="pdT20 pdB10">
                                    <slideVerify
                                        v-model:value="dataForm.sliderFlag"
                                        @update="updateSlideVerify"
                                        :key="sliderKey"
                                        ref="slideVerifyRef"
                                    ></slideVerify>
                                </el-col>
                                <el-col :span="24" type="flex" justify="center">
                                    <el-button
                                        type="warning"
                                        class="h40 mgT10"
                                        round
                                        style="opacity: 1; width: 100%"
                                        @click="submitForm"
                                        :disabled="btnSubmitFlag"
                                        >{{ loginMode === "login" ? btnSubmitMsg : "立即注册" }}</el-button
                                    >
                                </el-col>
                            </el-row>
                            <el-row v-if="loginMode === 'login'">
                                <el-col :span="24" class="fs14 textR color9 pdR20">
                                    <router-link to="/">忘记密码？</router-link>
                                </el-col>
                            </el-row>
                        </el-form>

                        <div class="card-footer textC mgT20">
                            <p class="color9 fs12">{{ copyright }}</p>
                        </div>
                    </el-card>
                </div>
            </el-main>
        </el-container>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onBeforeMount, onMounted, onUnmounted, getCurrentInstance, watch, computed } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage, ElLoading } from "element-plus";
import slideVerify from "@/components/slideVerify.vue";
import { setLocal, getLocal } from "@/assets/js/funcs";
import store from "@/store";

const { proxy } = getCurrentInstance() as any;

const pcHeight = ref(document.body.clientHeight + "px");
const pcHeight2 = ref(document.body.clientHeight - 240 + "px");
const copyright = ref("© " + new Date().getFullYear() + " 就业职通车  版权所有      粤ICP备XXXXXXXXXX号");

const btnSubmitFlag = ref(false);
const btnSubmitMsg = ref("登 录");

// 为登录和注册模式分别创建独立的验证码状态
const loginCodeWaiting = ref(false);
const registerCodeWaiting = ref(false);
const loginCodeText = ref("获取验证码");
const registerCodeText = ref("获取验证码");
// 用于保存定时器ID，方便清除
const loginIntervalId = ref<number | null>(null);
const registerIntervalId = ref<number | null>(null);

// 计算属性，根据当前模式返回相应的状态
const getCodeisWaiting = computed(() => {
    return loginMode.value === "login" ? loginCodeWaiting.value : registerCodeWaiting.value;
});

const getCodeText = computed(() => {
    return loginMode.value === "login" ? loginCodeText.value : registerCodeText.value;
});

const inputRef = ref<HTMLInputElement | null>(null);
const dataFormRef = ref<FormInstance | null>(null);
const slideVerifyRef = ref(null);
const sliderKey = ref(0); // 用于强制重新渲染滑块组件

// 登录模式状态
const loginMode = ref("login"); // 'login' 或 'register'

// 切换登录/注册模式
const switchMode = (mode: string) => {
    if (mode === loginMode.value) return;

    loginMode.value = mode;
    dataForm.account = "";
    dataForm.password = "";
    dataForm.smsCode = "";
    dataForm.sliderFlag = false;

    if (mode === "register") {
        dataForm.confirmPassword = "";
    }

    // 重置表单验证
    if (dataFormRef.value) {
        dataFormRef.value.clearValidate();
    }

    // 通过改变key值强制重新渲染滑块组件
    sliderKey.value += 1;

    // 聚焦到第一个输入框
    setTimeout(() => {
        if (inputRef.value) {
            inputRef.value.focus();
        }
    }, 100);
};

const dataForm = reactive({
    account: "",
    password: "",
    confirmPassword: "",
    smsCode: "",
    sliderFlag: false,
});

// 验证两次密码是否一致的函数
const validatePass = (rule: any, value: string, callback: any) => {
    if (value === "") {
        callback(new Error("请再次输入密码"));
    } else if (value !== dataForm.password) {
        callback(new Error("两次输入密码不一致!"));
    } else {
        callback();
    }
};

const dataRules = reactive<FormRules>({
    account: [
        { required: true, message: "请输入登录账号", trigger: "blur" },
        { min: 5, max: 20, message: "登录账号为5-20个字符", trigger: "blur" },
    ],
    password: [
        {
            required: true,
            message: "请输入登录账号密码",
            trigger: "blur",
        },
        {
            min: 5,
            max: 30,
            message: "登录账号密码为5-30个字符",
            trigger: "blur",
        },
    ],
    confirmPassword: [
        {
            required: true,
            message: "请再次输入密码",
            trigger: "blur",
        },
        { validator: validatePass, trigger: "blur" },
    ],
    smsCode: [
        {
            required: true,
            message: "请输入有效的验证码",
            trigger: "blur",
        },
        { min: 6, max: 6, message: "验证码为6个字符", trigger: "blur" },
    ],
});

onBeforeMount(() => {});

onMounted(() => {
    if (getLocal("gdepUserInfo")) {
        proxy.$func.openPage("/company");
    }
    if (inputRef.value) {
        inputRef.value.focus();
    }
});

const sendSmsCode = async () => {
    if (dataForm.account.length > 20 || dataForm.account.length < 5) {
        ElMessage.error("请填写正确的登录账号");
        return false;
    }

    // 根据当前模式设置相应的状态
    if (loginMode.value === "login") {
        loginCodeText.value = "发送中...";
        loginCodeWaiting.value = true;
    } else {
        registerCodeText.value = "发送中...";
        registerCodeWaiting.value = true;
    }

    btnSubmitFlag.value = true;

    // 模拟API请求延迟
    setTimeout(() => {
        // 模拟成功获取验证码
        dataForm.smsCode = "123456";
        btnSubmitFlag.value = false;
        setTimer();
        ElMessage.success("验证码已发送，请注意查收");
    }, 1000);

    // 真实API调用（目前注释）
    // const smsResult: any = await sso.apiGetSendCode({
    //     account: dataForm.account
    // });

    // if (loginMode.value === 'login') {
    //     loginCodeText.value = "获取验证码";
    //     loginCodeWaiting.value = false;
    // } else {
    //     registerCodeText.value = "获取验证码";
    //     registerCodeWaiting.value = false;
    // }
    // btnSubmitFlag.value = false;

    // if (smsResult.code === 1) {
    //     if (smsResult.data && smsResult.data.sms_code) {
    //         dataForm.smsCode = smsResult.data.sms_code;
    //         setTimer();
    //         ElMessage.success(smsResult.msg);
    //         dataFormRef.value.validateField("smsCode");
    //     } else {
    //         ElMessage.error("系统获取验证码为空，请重新发送");
    //     }
    // } else {
    //     ElMessage.error(smsResult.msg);
    // }
};

const setTimer = () => {
    const holdTime = ref(60); // 修改为60秒
    const isLogin = loginMode.value === "login";

    // 清除可能存在的旧定时器
    if (isLogin && loginIntervalId.value) {
        clearInterval(loginIntervalId.value);
    } else if (!isLogin && registerIntervalId.value) {
        clearInterval(registerIntervalId.value);
    }

    // 设置相应模式的文本
    if (isLogin) {
        loginCodeText.value = "重发(" + holdTime.value + ")";
    } else {
        registerCodeText.value = "重发(" + holdTime.value + ")";
    }

    const intervalId = window.setInterval(() => {
        if (holdTime.value > 0) {
            if (isLogin) {
                loginCodeWaiting.value = true;
                loginCodeText.value = "重发(" + holdTime.value + ")";
            } else {
                registerCodeWaiting.value = true;
                registerCodeText.value = "重发(" + holdTime.value + ")";
            }
            holdTime.value--;
        } else {
            if (isLogin) {
                loginCodeWaiting.value = false;
                loginCodeText.value = "获取验证码";
                if (loginIntervalId.value) clearInterval(loginIntervalId.value);
            } else {
                registerCodeWaiting.value = false;
                registerCodeText.value = "获取验证码";
                if (registerIntervalId.value) clearInterval(registerIntervalId.value);
            }
            clearInterval(intervalId);
        }
    }, 1000);

    // 保存定时器ID
    if (isLogin) {
        loginIntervalId.value = intervalId;
    } else {
        registerIntervalId.value = intervalId;
    }
};

const submitForm = () => {
    if (!dataFormRef || !dataFormRef.value) return;
    dataFormRef.value.validate(async (valid: boolean) => {
        if (valid) {
            // 根据当前模式执行不同的操作
            if (loginMode.value === "login") {
                // 登录逻辑
                if (dataForm.account != "admin" || dataForm.password != "123456" || dataForm.smsCode != "123456") {
                    ElMessage.error("请填写正确的登录信息");
                    return;
                }
                if (dataForm.sliderFlag == false) {
                    ElMessage.error("请拖动滑块到最右边完成验证");
                    return;
                }

                var obj = {
                    account: dataForm.account,
                    password: dataForm.password,
                    sliderFlag: dataForm.sliderFlag,
                    login_type: 1,
                };

                btnSubmitFlag.value = true;
                btnSubmitMsg.value = "登录中...";

                // 模拟登录成功
                setLocal("gdepUserInfo", {
                    account: dataForm.account,
                    short_name: "",
                    user_name: "",
                    role_name: "",
                    type: "company",
                    token: "company-token-" + Date.now(), // 生成一个临时token
                });
                ElMessage.success("登录成功");
                proxy.$func.openPage("/company/index");
            } else {
                // 注册逻辑
                if (dataForm.sliderFlag == false) {
                    ElMessage.error("请拖动滑块到最右边完成验证");
                    return;
                }

                if (dataForm.password !== dataForm.confirmPassword) {
                    ElMessage.error("两次输入的密码不一致");
                    return;
                }

                btnSubmitFlag.value = true;

                // 这里添加注册API调用
                // const regResult: any = await sso.apiRegister({
                //     account: dataForm.account,
                //     password: dataForm.password,
                //     smsCode: dataForm.smsCode,
                // });

                // 模拟注册成功
                setTimeout(() => {
                    btnSubmitFlag.value = false;
                    ElMessage.success("注册成功，请登录");
                    switchMode("login");
                }, 1000);
            }
        }
    });
};

const updateSlideVerify = (e: boolean) => {
    dataForm.sliderFlag = e;
};

onUnmounted(() => {});
</script>

<style scoped>
.loginPC {
    width: 100%;
    position: relative;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
}

.background-image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    z-index: -1;
}

.login-card-container {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
}

.login-card {
    width: 400px;
    border-radius: 16px;
    padding: 20px;
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.card-header {
    text-align: center;
    padding-bottom: 10px;
}

.card-footer {
    margin-top: 20px;
    padding-top: 15px;
}

.mode-switch {
    text-align: center;
    margin-bottom: 10px;
}

.mode-switch .el-button-group {
    width: 80%;
}

.mode-switch .el-button-group .el-button {
    width: 50%;
}

.active-btn {
    font-weight: bold;
}
</style>
